﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;

/// <summary>
/// Summary description for CFile
/// </summary>
public class CFile
{
    CMauVirus cMau;
	public CFile()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }

    public bool CreateZip(string idMau)
    {
        cMau = new CMauVirus();
        string nameVirus = cMau.GetNameMauFromID(idMau);
        string pathData = System.Web.Configuration.WebConfigurationManager.AppSettings["dataPath"].ToString();
        string pathAllFile = pathData + "/" + idMau;
        try
        {
            string[] filenames = Directory.GetFiles(pathAllFile);
            if (!System.IO.File.Exists(pathAllFile + "\\" + nameVirus + ".zip"))
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(pathAllFile + "\\" + nameVirus + ".zip")))
                {
                    s.SetLevel(9);
                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {

                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);

                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
            }
            else
            {

            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public bool CheckExitsFileOrDirect(string type, string path)
    {
        if (type == "0")
        {
            if (Directory.Exists(path)) return true;
        }
        else if (type == "1")
        {
            DirectoryInfo directInfo = new DirectoryInfo(path);
            FileInfo[] listFiles = directInfo.GetFiles("*.*");
            if (listFiles.Length > 0) return true;
        }
        return false;
    }

}